﻿using Delphi.Mimir.Config;
using Delphi.Mimir.Data.Entities.Final;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Delphi.Mimir.Wrapper {
    public class LoadControlWrapper {
        public static ICollection<LoadControl> GetLoadControls(Exchange exchange) {
            ICollection<LoadControl> lcs = new List<LoadControl>();
            using(var conntext = new DelphiContext()) {
                lcs = conntext.LoadControls
                    .Include("LoadType")
                    .Include("Frequency")
                    .Include("Exchange")
                    .Include("Exchange.TimeZone")
                    .Where(a => a.ExchangeId == exchange.ExchangeId)
                    .ToList<LoadControl>();
            }
            return lcs;
        }

        public static ICollection<LoadControl> GetLoadControls(string exchangeCode) {
            ICollection<LoadControl> lcs = new List<LoadControl>();
            Exchange e = new Exchange();
            using(var conntext = new DelphiContext()) {
                e = conntext.Exchanges.Where(a => a.Code == exchangeCode).FirstOrDefault<Exchange>();
            }
            lcs = GetLoadControls(e);
            return lcs;
        }

        public static void AddNewLoad(int loadControlId, DateTime tradeDate, int records, string status) {
            using(var conntext = new DelphiContext()) {
                LoadControl lc = conntext.LoadControls.Where(a => a.LoadControlId == loadControlId).FirstOrDefault();
                Load load = new Load();
                load.LoadControl = lc;
                load.LoadTime = DateTime.UtcNow;
                load.TradeDate = tradeDate;
                load.Records = records;
                load.Status = status;
                conntext.Loads.Add(load);
                conntext.SaveChanges();
            }
        }

        public static void AddNewLoad(string exchangeCode, string loadType, DateTime tradeDate, int records, string status) {
            AddNewLoad(GetLoadControl(exchangeCode, loadType).LoadControlId, tradeDate, records, status);
        }

        public static LoadControl GetLoadControl(string exchangeCode, string loadType) {
            LoadControl lc = new LoadControl();

            using(var context = new DelphiContext()) {
                lc = context.LoadControls.Where(a => a.Exchange.Code == exchangeCode
                                                    && a.LoadType.Code == loadType).FirstOrDefault();
            }
            return lc;
        }
    }
}
